﻿using RightControl.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace AlibabaCollector {
    public class ImageUtil {
        /// <summary>
        /// 自动抠白底图
        /// </summary>
        /// <param name="imageUrl"></param>
        public static void GetImageWithoutBackground(string imageUrl) {
            using (var client = new HttpClient())
            using (var formData = new MultipartFormDataContent()) {
                formData.Headers.Add("X-Api-Key", "QXE4b4cAihoWVSPDxKRTnFxg");
                formData.Add(new StringContent(imageUrl), "image_url");
                formData.Add(new StringContent("auto"), "size");
                var response = client.PostAsync("https://api.remove.bg/v1.0/removebg", formData).Result;
                string filePath = Configs.GetValue("ImgTempDir") + "\\nobackground\\nb_" + imageUrl.Substring(imageUrl.LastIndexOf("/") + 1);
                //string filePath = @"D:\install\电商资料\TemporaryImage\nobackground" + "\\nb_" + imageUrl.Substring(imageUrl.LastIndexOf("/") + 1);
                if (response.IsSuccessStatusCode) {
                    FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
                    response.Content.CopyToAsync(fileStream).ContinueWith((copyTask) => { fileStream.Close(); });
                }
                else {
                    Console.WriteLine("Error: " + response.Content.ReadAsStringAsync().Result);
                }
            }
        }
    }
}
